const app = require('express')();
var express = require('express');
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
const spawn = require('child_process').spawn;


app.use(express.static('public'));


app.get('/', (req, res) => {
  res.sendFile(__dirname + '/code.html');
});
app.get('/index', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
app.get('/watch', (req, res) => {
  res.sendFile(__dirname + '/watch.html');
});


app.get('/teacher', (req, res) => {
  res.sendFile(__dirname + '/teacher.html');
});

// justwritecode
app.get('/justwritecode', (req, res) => {
  res.sendFile(__dirname + '/justwritecode.html');
});
io.on('connection', (socket) => {
  socket.on('chat message', msg => {
    io.emit('chat message', msg);
  });
  socket.on('teacher code', msg => {
    io.emit('teacher code', msg);
  });
  socket.on('run code', msg => {
    
    console.log(msg)
    io.emit('run code', msg);
    var fs = require('fs');

    var data = msg;
    fs.writeFile('Demo.java', data, function (err) {
        if (err) {
            console.log(err);
        } else {
            console.log('ok.');
        }
    });
  });
  
});

http.listen(80, '0.0.0.0', () => {
  console.log(`Socket.IO server running at http://0.0.0.0:${port}/`);
});
